package main

import (
	"bufio"
	"fmt"
	"gmfs/core"
	"os"
	"runtime"
	"strconv"
	"strings"
)

var helpText = `
gmfs - the notes helper

actions:

  gmfs help

  gmfs test

  gmfs start
`

const config = "conf/config.json"

func main() {
	if len(os.Args) == 1 {
		help(0)
	}
	action := os.Args[1]
	switch action {
	case "help":
		help(0)
	case "test":
		handleNew()
	case "start":
		core.StartServer(config)
	default:
		help(0)
	}
}

func handleNew() {
	ipt := acceptInput("Enter the start server , using CPU cores '0 .. ': ")
	if ipt != "" {
		cpucores, err := strconv.Atoi(ipt)
		if err != nil {
			panic(err)
		}
		fmt.Printf("using %d CPU cores\n", cpucores)
		runtime.GOMAXPROCS(cpucores)
		core.StartServer(config)
	} else {
		help(1)
	}
}

/**
 * 打印帮助信息
 */
func help(exit int) {
	fmt.Println(helpText)
	os.Exit(exit)
}

/**
 * 读取命令行输入
 */
func acceptInput(question string) string {
	reader := bufio.NewReader(os.Stdin)
	var (
		response string
		err      error
	)
	for response == "" {

		fmt.Print(question)
		response, err = reader.ReadString('\n')
		if err != nil {
			fmt.Println("Oops, what was that?")
			os.Exit(1)
		}
		response = strings.TrimSpace(response)
	}
	return response
}
